//
//  UMPushHelper.m
//  RNUpush
//
//  Created by mac on 2022/5/26.
//

#import "UMPushHelper.h"
#import "RNUpush.h"
#import <UMPush/UMessage.h>
@interface UMPushHelper()
@end

@implementation UMPushHelper

+(instancetype)share{
  static UMPushHelper * helper = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    if(helper == nil){
        helper = [[self alloc]  init];
    }
  });

  return helper;
}
-(id)init{
  self = [super init];
  if(self){
      [UNUserNotificationCenter currentNotificationCenter].delegate=self;
  }
  return  self;
}

-(void)registerForRemoteNotificationsWithLaunchOptions:(NSDictionary *)launchOptions{
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }else{
        }
    }];
    
    [UMessage setBadgeClear:YES];
    [UMessage setAutoAlert:NO];
}


//iOS10以下使用这两个方法接收通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
  [UMessage setAutoAlert:NO];
   if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
     NSMutableDictionary * userInfoWrapper = [NSMutableDictionary dictionaryWithDictionary:userInfo];
     [userInfoWrapper setValue:@(0) forKey:@"pop"];
     [UMessage didReceiveRemoteNotification:userInfoWrapper];
     [RNUpush emitEventPayload:userInfoWrapper];
   }

        //过滤掉Push的撤销功能，因为PushSDK内部已经调用的completionHandler(UIBackgroundFetchResultNewData)，
   //防止两次调用completionHandler引起崩溃
   if(![userInfo valueForKeyPath:@"aps.recall"])
   {
       completionHandler(UIBackgroundFetchResultNewData);
   }
  
}
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
  NSDictionary * userInfo = notification.request.content.userInfo;
//      NSLog(@"sg willPresentNotification %@",userInfo);
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
      [UMessage setAutoAlert:NO];
      //应用处于前台时的远程推送接受
      //必须加这句代码
    NSMutableDictionary * userInfoWrapper = [NSMutableDictionary dictionaryWithDictionary:userInfo];
    [userInfoWrapper setValue:@(0) forKey:@"pop"];
    [UMessage didReceiveRemoteNotification:userInfoWrapper];
    [RNUpush emitEventPayload:userInfoWrapper];
  }else{
      //应用处于前台时的本地推送接受
  }
  completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
      //应用处于后台时的远程推送接受
      //必须加这句代码
      
      NSMutableDictionary * userInfoWrapper = [NSMutableDictionary dictionaryWithDictionary:userInfo];
      [userInfoWrapper setValue:@(1) forKey:@"pop"];
      [UMessage didReceiveRemoteNotification:userInfoWrapper];
      [RNUpush emitEventPayload:userInfoWrapper];
  }else{
      //应用处于后台时的本地推送接受
  }
}

//#include <arpa/inet.h>
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    if (![deviceToken isKindOfClass:[NSData class]]) return;
    const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    NSLog(@"deviceToken:%@",hexToken);
    //1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    //传入的devicetoken是系统回调didRegisterForRemoteNotificationsWithDeviceToken的入参，切记
    //[UMessage registerDeviceToken:deviceToken];
    self.devicetoken =hexToken ;
}

@end
